#!/bin/sh
# ./ry.sh start 启动 stop 停止 restart 重启 status 状态
#输入两个参数，一个是操作名，一个是应用名称。

function init()
{   
    #name=$2
    #AppName=`sudo find ~/envpro -name ${name}`

    # JVM参数
    #JVM_OPTS="-Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Xlog:gc*,:time,tags,level -XX:+UseZGC"
    
    #JVM_OPTS="-Dfile.encoding=utf-8"
    #APP_HOME=`pwd`
    #LOG_PATH=$APP_HOME/logs/$AppName.log

    if [ "$1" = "" ];
    then
        echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
        exit 1
    fi

    if [ "$2" = "" ];
    then
        echo -e "\033[0;31m 未输入或找不到应用名 \033[0m"
        exit 1
    fi
}


function start()
{
    AppName=$1
    APP_HOME=`pwd`
    AppNamePwd=`sudo find ${APP_HOME} -name ${AppName}.jar`

    # JVM参数
    #JVM_OPTS="-Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Xlog:gc*,:time,tags,level -XX:+UseZGC"
    JVM_OPTS="-Dfile.encoding=utf-8"
    APP_HOME=`pwd`
    LOG_PATH=$APP_HOME/logs/$AppName.log
    
    #PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
    PID= ps x|grep java|grep $AppName|awk '{print $1}'
    if [ x"$PID" != x"" ]; then
        echo "$AppName is running..."
    else
        echo "nohup java ${JVM_OPTS} -jar ${AppNamePwd} > /dev/null 2>&1 &"
	    nohup java $JVM_OPTS -jar $AppNamePwd > /dev/null 2>&1 &
        echo "Start $AppName success..."
    fi
}

function stop()
{
    AppName=$1
    echo "Stop $AppName"

    PID=""
    query(){
        PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
    }

    query
    if [ x"$PID" != x"" ]; then
        kill -TERM $PID
        echo "$AppName (pid:$PID) exiting..."
        while [ x"$PID" != x"" ]
        do
            sleep 1
            query
        done
        echo "$AppName exited."
    else
        echo "$AppName already stopped."
    fi
}

function restart()
{
    stop $AppName
    sleep 2
    start $AppName $JVM_OPTS
}

function status()
{
    AppName=$1
    PID=`ps -ef |grep java|grep $AppName|grep -v grep|wc -l`
    if [ $PID != 0 ];then
        echo "$AppName is running..."
    else
        echo "$AppName is not running..."
    fi
}

#被其他调用，输入两个参数
#输入两个参数，一个是操作名，一个是应用名称。
#参数1:start 启动 stop 停止 restart 重启 status 状态
#参数2:应用名称。然后查找路径并执行相应启动或停。
function exec()
{
    init $1 $2
    JVM_OPTS=JVM_OPTS="-Dfile.encoding=utf-8"
    case $1 in
        start)
        start $2 $JVM_OPTS;;
        stop)
        stop $2;;
        restart)
        restart $2 $JVM_OPTS;;
        status)
        status $2;;
        *)
    esac
}
